package com.welson.db.cryptor.strategy;

import com.welson.db.cryptor.config.DbCryptorProperties;

import javax.crypto.Cipher;
import java.util.Arrays;

/**
 * 加解密策略抽象基类
 * @author welson
 */
public abstract class AbstractCryptStrategy implements CryptStrategy {
    protected final DbCryptorProperties properties;
    protected final String algorithm;

    protected AbstractCryptStrategy(DbCryptorProperties properties, String algorithm) {
        this.properties = properties;
        this.algorithm = algorithm;
    }

    /**
     * 获取Cipher实例
     */
    public abstract Cipher getCipher(String transformation) throws Exception;

    /**
     * 验证加密模式
     */
    public abstract void validateMode(String mode);

    /**
     * 判断模式是否需要IV
     */
    protected boolean isModeRequireIv(String mode) {
        return Arrays.asList("CBC", "CFB", "OFB", "CTR").contains(mode);
    }

    /**
     * 获取转换字符串
     */
    protected String getTransformation() {
        return algorithm + "/" + properties.getMode() + "/" + properties.getPadding();
    }

    /**
     * 获取当前模式
     */
    protected String getCurrentMode() {
        return properties.getMode().toUpperCase();
    }
} 